from django.shortcuts import render

from rest_framework.response import Response

from rest_framework.views import APIView

from cart import cartser
from cart.models import CartModel
from utils.authorization import MyAuthentication


# Create your views here.


class AddCart(APIView):
    authentication_classes = [MyAuthentication, ]
    def post(self,request):
        user = request.data.get("user","")
        course = request.data.get("course","")
        if user and course:
            info = CartModel.objects.filter(user=user,course=course).first()
            if info:
                return Response({"msg":"课程已经存在"})
            else:
                ser = cartser.CartSerializer(data=request.data)
                if ser.is_valid():
                    ser.save()
                    return Response({"msg":"添加成功"})
                else:
                    return Response({"msg":ser.errors})
        else:
            return Response({"detail":"参数错误"})

class CartList(APIView):
    authentication_classes = [MyAuthentication, ]
    def get(self,request):
        user = request.query_params.get("user","")
        if user=="":
            return Response({"detail":"参数错误"})
        cart = CartModel.objects.filter(user=user)
        ser = cartser.CartSerializer(cart,many=True)
        return Response({"msg":'success', "data": ser.data})

class ChangeOne(APIView):
    authentication_classes = [MyAuthentication,]
    def put(self,request):
        id=request.data.get("id","")
        if id=="":
            return Response({"detail":"参数错误"})
        cart=CartModel.objects.filter(id=id).first()
        cart.select=not cart.select
        cart.save()
        return Response({"msg":'修改成功'})

class ChangeAll(APIView):
    authentication_classes = [MyAuthentication, ]
    def put(self,request):
        user = request.data.get("user","")
        select = request.data.get("select","")
        if user=="":
            return Response({"detail":"参数错误"})
        cart = CartModel.objects.filter(user=user)
        for i in cart:
            i.select=select
            i.save()
        return Response({"msg":"修改成功"})